<template>
  <div class="clearfix">
    <a-upload
      v-model:file-list="fileList"
      :custom-request="customRequest"
      :max-count="1"
      list-type="picture-card"
      @preview="handlePreview"
      @change="handleChange"
      @remove="handleRemove"
      :locale="{
        uploading: '上传中...',
      }"
      :disabled="uploadLoading"
    >
      <div>
        <plus-outlined />
        <div style="margin-top: 8px">点击上传</div>
      </div>
    </a-upload>
    <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import { ref, watch, toRef } from 'vue'
import type { UploadProps } from 'ant-design-vue'
import { uploadImage } from '@/api/uploadController'
import { message } from 'ant-design-vue'

interface props {
  fileUrl: string | undefined
}

interface Emits {
  (e: 'update:fileUrl', value: string): void
}

const props = withDefaults(defineProps<props>(), {
  fileUrl: '',
})

const emit = defineEmits<Emits>()

const fileUrl = toRef<string>(props.fileUrl)
const isResetUrl = ref<string>(props.fileUrl)

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

const uploadLoading = ref<boolean>(false)

const fileList = ref<UploadProps['fileList']>([
  // {
  //   uid: '-xxx',
  //   percent: 50,
  //   name: 'image.png',
  //   status: 'uploading',
  //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  // },
  // {
  //   uid: '-5',
  //   name: 'image.png',
  //   status: 'error',
  // },
])

const handleChange = async (file: UploadProps['fileList'][number]) => {
  console.log(file, 'file')
  // debugger
}

// 移除文件
const handleRemove = (file: UploadProps['fileList'][number]) => {
  fileList.value = fileList.value?.filter((item) => item.uid !== file?.uid) || []
  fileUrl.value = ''
}

// 发送上传文件请求
const customRequest = async (options: any) => {
  // console.log(options,'options')
  uploadLoading.value = true
  const { onSuccess, onError, file, onProgress } = options
  const fmData = new FormData()
  // const config = {
  //   headers: { 'content-type': 'multipart/form-data' },
  // }
  fmData.append('file', file)
  try {
    const res = await uploadImage(fmData)
    console.log(fileList.value, 'fileList')
    if (res.data.code === 0 && res.data.data) {
      message.success('上传成功')
      fileUrl.value = res.data.data
      onSuccess(res)
    } else {
      message.error(res.data.message || '上传失败')
      fileList.value = []
      isResetUrl.value &&
        fileList.value.push({
          uid: '-1',
          name: 'xxx.png',
          status: 'done',
          url: isResetUrl.value,
        })
    }
  } catch (error: any) {
    console.log('Error', error)
    onError({ error })
    message.error('上传失败')
    fileList.value = []
    isResetUrl.value &&
      fileList.value.push({
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: isResetUrl.value,
      })
  } finally {
    uploadLoading.value = false
  }
}

const handleCancel = () => {
  previewVisible.value = false
  // previewTitle.value = '';
}
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  console.log(file, fileList.value, 'file12')
  debugger
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  // previewImage.value = file.url || file.preview;
  previewImage.value = fileUrl.value || file.preview
  previewVisible.value = true
  // previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
}

watch(
  () => props.fileUrl,
  (newVal) => {
    if (newVal === isResetUrl.value) fileList.value = []
    if (newVal && isResetUrl.value === newVal) {
      fileList.value?.push({
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: newVal,
      })
    }
  },
  { immediate: true, deep: true },
)

watch(
  fileUrl,
  (newVal) => {
    debugger
    emit('update:fileUrl', fileUrl.value)
    newVal &&
      !fileList.value?.length &&
      fileList.value?.push({
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: newVal,
      })
  },
  { immediate: true },
)
</script>
<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
